package middlewares

import (
	"github.com/gin-gonic/gin"
	"menu-generation-go/database"
	"menu-generation-go/handlers/common"
	"menu-generation-go/models"
	"menu-generation-go/utils"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if token == "" {
			common.SendErrJSON("用户令牌异常", c)
			c.Abort()
			return
		}

		claims, err := utils.ParseToken(token)
		if err != nil {
			common.SendErrJSON("无效的用户令牌", c)
			c.Abort()
			return
		}
		// 检查会话是否有效
		var session models.UserSession
		if err := database.DB.Where("id = ? AND is_active = true AND expires_at > NOW()", claims.SessionID).First(&session).Error; err != nil {
			common.SendErrJSON("会话已失效", c)
			return
		}
		// 将用户ID存入上下文
		c.Set("user_session", session)
		c.Set("user_id", claims.UserID)
		c.Next()
	}
}
